import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios';

/**
 * 借助 createAsyncThunk，创建异步操作函数， 会返回一个异步的 action
 */
export const fetchHomeMultidataAction = createAsyncThunk("fetch/homeMultidata", async () => {
  const res = await axios.get("http://123.207.32.32:8000/home/multidata")
  return res.data;
})

//写法3：不借助extraReducers，手动进行dispatch, (还可以在dispatch本方法时，传入参数, 通过extraInfo获取)
// export const fetchHomeMultidataAction = createAsyncThunk(
//   "fetch/homeMultidata", 
//   async (extraInfo, store) => {
//     //发送网络请求，获取数据
//     const res = await axios.get("http://123.207.32.32:8000/home/multidata")
//     //取出数据，直接在此处进行dispatch
//     const banners = res.data.data.banner.list;
//     const recommends = res.data.data.recommend.list;
//     store.dispatch(changeBanners(banners))
//     store.dispatch(changeRecommends(recommends))
//   }
// )
const homeSlice = createSlice({
  name: 'name',
  //data
  initialState: {
    banners: [],
    recommends: []
  },
  reducers: {
    changeBanners(state, action) {
      state.banners = action.payload
    },
    //解构 action
    changeRecommends(state, { payload }) {
      state.recommends = payload;
    }
  },
  // 写法1：额外的reducer，针对异步操作监听状态,
  // createAsyncThunk创建出来的action被dispatch时，会存在三种状态：
  // pending: action被发出，但是还没有最终的结果
  // fulfilled: 获取到最终的结果（有返回值的结果）
  // rejected: 执行过程中有错误或者抛出了异常
  extraReducers: {
    //计算属性名语法：取出 fetchHomeMultidataAction.pending 作为方法名
    [fetchHomeMultidataAction.pending](state, action) {
      console.log("pending");
    },
    [fetchHomeMultidataAction.fulfilled](state, action) {
      console.log("fulfilled");
      state.banners = action.payload.data.banner.list;
      state.recommends = action.payload.data.recommend.list;
    },
    [fetchHomeMultidataAction.rejected](state, action) {
      console.log("rejected");
    }
  }

  // 写法2：链式操作
  // extraReducers: (builder) => {
  //   builder.addCase(fetchHomeMultidataAction.pending, (state, action) => {
  //     console.log("pending");
  //   }).addCase(fetchHomeMultidataAction.fulfilled, (state, { payload }) => {
  //     state.banners = payload.data.banner.list;
  //     state.recommends = payload.data.recommend.list;
  //   })
  // }
})

export const { changeBanners, changeRecommends } = homeSlice.actions
export default homeSlice.reducer